package com.liu.system.manage.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.liu.common.utils.IdWorker;
import com.liu.system.manage.domain.DUser;
import com.liu.system.manage.mapper.UserMapper;
import com.liu.system.manage.service.IUserService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.util.Date;
import java.util.List;


@Service
@Slf4j
@Transactional
public class UserServiceImpl extends ServiceImpl<UserMapper, DUser> implements IUserService {

    @Autowired
    UserMapper userMapper;

    @Autowired
    IdWorker idWorker;

    @Autowired
    BCryptPasswordEncoder bCryptPasswordEncoder;

    @Override
    public List<DUser> findAllUser() {
        return userMapper.findAllUser();
    }

    @Override
    public boolean insert(DUser duser) {
        duser.setId(idWorker.nextId()+"");
        duser.setPassword(bCryptPasswordEncoder.encode(duser.getIphone()));
        return this.save(duser);
    }

    @Override
    public IPage<DUser> queryUserForPage(int page, int rows, String query) {

        IPage<DUser> userPage = new Page<>(page, rows);
        QueryWrapper<DUser> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(query)) {
            wrapper.like("name", query).or().like("nick_name", query).or().like("iphone", query);
        }
        userPage = userMapper.selectPage(userPage, wrapper);

        log.info("page：" + page);
        log.info("rows：" + rows);
        log.info("query：" + query);

        log.info("总数：" + userPage.getTotal());
        log.info("总页数：" + userPage.getPages());


        return userPage;
    }

    @Override
    public boolean update(DUser user) {
        QueryWrapper<DUser> params = new QueryWrapper<>();
        params.eq("id",user.getId());
        user.setUpdateTime(null);
        user.setCreateTime(null);
        return this.update(user);
    }


    public boolean delete(String id) {

        return  this.removeById(id);
    }

}
